//
//  ArtDatabaseVC.m
//  jingdongfang
//
//  Created by MTiMac01 on 2017/8/21.
//  Copyright © 2017年 LJL. All rights reserved.
//

#import "ArtDatabaseVC.h"
#import "FindLayout.h"
#import "ArtGalleryCell_third.h"
#import "FilterV.h"
#import "AppDelegate.h"
#import "IGDatabaseApi.h"
#import "IGArtLibraryApi.h"
#import "XiangQingViewController.h"
@interface ArtDatabaseVC ()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>
{
    UICollectionView *collect;
    BOOL isShow;
    NSString *searchKey;//查询条件
    NSString *pageNumber;//页数，从0开始
    NSString *pageSize;//一页显示列表数
    NSString *queryTime;//查询时间
}
@property (nonatomic, strong)FilterV *filterView;
@property (nonatomic, strong)IGArtLibraryApi *artLibraryApi;
@property (nonatomic, strong)NSMutableArray *artLibraryArr;
@property (nonatomic, strong)IGDatabaseApi *api;
@property (nonatomic, strong)NSMutableArray *dataArr;

@end                                                     

@implementation ArtDatabaseVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self loadUI];
    [self creatNav];
    [self dataRequest];
}

- (void)creatNav
{
//    self.navigationItem.title = @"艺术库";
    self.navigationItem.title = NSLocalizedString(@"Gallery", nil);
//    [self ig_setupRightButtonItemWithTitle:@"筛选" image:nil highLightedImage:nil];
    [self ig_setupRightButtonItemWithTitle:NSLocalizedString(@"Filter", nil) image:[UIImage imageNamed:@"形状33"] highLightedImage:[UIImage imageNamed:@"形状33"]];
}

- (void)ig_rightButtonPressed:(id)sender
{
    if (_artLibraryArr.count)
    {
        self.filterView.dataSource = self.artLibraryArr;
        [self.filterView.collectionV reloadData];
        isShow = !isShow;
        if (isShow)
        {
            [self showFilterView];
        }
        else
        {
            [self hideFilterView];
        } 
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self hideFilterView];
}

- (void)showFilterView
{
    [UIView animateWithDuration:0.2 animations:^{
        self.filterView.frame = CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT);
    }];
}

- (void)hideFilterView
{
    [UIView animateWithDuration:0.2 animations:^{
        self.filterView.frame = CGRectMake(KSCREENWIDTH, 0, KSCREENWIDTH, KSCREENHEIGHT);
    }];
}

- (void)loadUI
{
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)])
    {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    FindLayout *layout = [[FindLayout alloc] init];
    collect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT - NavigationMagin) collectionViewLayout:layout];
    collect.backgroundColor = RGB(234, 234, 234);
    collect.alwaysBounceVertical = YES;
    collect.delegate = self;
    collect.dataSource = self;
    [collect registerClass:[ArtGalleryCell_third class] forCellWithReuseIdentifier:@"ArtGalleryCell_third"];
    @KWeakObj(self)
    [collect ig_setHeaderWithRefreshingBlock:^{
        [selfWeak dataRequest1];
    }];
    [self.view addSubview:collect];
    
    self.filterView = [[FilterV alloc] initWithFrame:CGRectMake(KSCREENWIDTH, 0, KSCREENWIDTH, KSCREENHEIGHT)];
    self.filterView.filterBlock = ^(NSMutableArray *arr) {
        isShow = !isShow;
        selfWeak.artLibraryArr = arr;
        [selfWeak hideFilterView];
    };
    __weak typeof(collect) weakCollect = collect;
    self.filterView.sureBlock = ^(NSMutableArray *arr) {
        isShow = !isShow;
        selfWeak.artLibraryArr = arr;
        [selfWeak hideFilterView];
        pageNumber = @"0";
        pageSize = @"10";
        queryTime = @"";
        [selfWeak dataRequest1];
        [weakCollect setContentOffset:CGPointMake(0, 0) animated:YES];
    };
    [[UIApplication sharedApplication].keyWindow addSubview:self.filterView];
    isShow = NO;
}

- (void)dataRequest
{
    searchKey = @"";
    pageNumber = @"0";
    pageSize = @"10";
    queryTime = @"";
    self.artLibraryApi = [IGArtLibraryApi new];
    self.api = [IGDatabaseApi new];
    self.dataArr = [@[] mutableCopy];
    self.artLibraryArr = [@[] mutableCopy];
    @KWeakObj(self)
    [self.artLibraryApi startWithDecodeClass:[IGArtLibraryResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject)
        {
            IGArtLibraryResp *resp = responseObject;
            IGArtLibraryModel *model = resp.data;
            selfWeak.artLibraryArr = [self addSelectStrWithArr:[model.lstClass mutableCopy]];
            [self dataRequest1];
        }
    }];
}

- (NSMutableArray *)addSelectStrWithArr:(NSMutableArray *)arr
{
    NSMutableArray *temp = [arr mutableCopy];
    for (int i = 0; i < arr.count; i++)
    {
        IGArtLibrary *lib = arr[i];
        IGArtLibrary *libTemp = temp[i];
        for (int j = 0; j < lib.lstSubClass.count; j++)
        {
            IGArtDetailLibrary *dic = libTemp.lstSubClass[j];
            dic.isSelect = @"0";
        }
    }
    return temp;
}

- (NSString *)findSelectKeyWithArr:(NSMutableArray *)arr
{
    NSMutableArray *temp = [@[] mutableCopy];
    for (int i = 0; i < arr.count; i++)
    {
        IGArtLibrary *lib = arr[i];
        NSMutableDictionary *dic = [@{@"id":@"", @"value":@""} mutableCopy];
        [dic setObject:lib.aId forKey:@"id"];
        NSString *str =@"";
        for (int j = 0; j < lib.lstSubClass.count; j++)
        {
            IGArtDetailLibrary *detailLib = lib.lstSubClass[j];
            if ([detailLib.isSelect isEqualToString:@"1"])
            {
                if ([str isEqualToString:@""] || !str)
                {
                    str = [NSString stringWithFormat:@"%@",detailLib.aId];
                }
                else
                {
                    str = [str stringByAppendingString:[NSString stringWithFormat:@",%@",str]];
                }
                [dic setObject:str forKey:@"value"];
            }
        }
        [temp addObject:dic];
    }
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:temp options:0 error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


- (void)dataRequest1
{
    @KWeakObj(self)
    searchKey = [self findSelectKeyWithArr:self.artLibraryArr];
    selfWeak.api.searchKey = searchKey;
    selfWeak.api.pageNumber = pageNumber;
    selfWeak.api.pageSize = pageSize;
    selfWeak.api.queryTime = queryTime;
    [self.api startWithDecodeClass:[IGDatabaseResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        [collect ig_endHeaderRefreshing];
        [collect ig_endFooterRefreshing];
        if (responseObject)
        {
            IGDatabaseResp *resp = responseObject;
            IGDatabaseModel *model = resp.data;
            if (model.lstWork && model.lstWork.count > 0)
            {
                [selfWeak setupFooter];
            }
            else
            {
                [collect ig_endFooterRefreshingWithNoMoreData];
            }
            queryTime = model.time;
            
            if ([pageNumber isEqualToString:@"0"])
            {
                _dataArr = [NSMutableArray arrayWithArray:model.lstWork];
            } else
            {
                [_dataArr addObjectsFromArray:model.lstWork];
            }
            [collect reloadData];
        }
        else
        {
            //空白页处理逻辑写在这里
        }
    }];
}

- (void)setupFooter
{
    @KWeakObj(self)
    [collect ig_setFooterWithRefreshingBlock:^{
        pageNumber = [NSString stringWithFormat:@"%ld", [pageNumber integerValue] + 1];
        [selfWeak dataRequest1];
    }];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArr.count?:0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ArtGalleryCell_third *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ArtGalleryCell_third" forIndexPath:indexPath];
    IGArtWorkModel *base = _dataArr[indexPath.item];
    cell.imgUrl = base.image;
    cell.titleL = base.title;
    [cell setNeedsLayout];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    IGArtWorkModel *base = _dataArr[indexPath.item];
    XiangQingViewController *vc = [[XiangQingViewController alloc] init];
    vc.p_id = base.aId;
    vc.isRoot = YES;
    [UIViewController ig_pushViewController:vc animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    IGArtWorkModel *base = _dataArr[indexPath.item];
    if ([base.plates integerValue]==1)
    {
        //横板
        return CGSizeMake((KSCREENWIDTH-16)/2, ((KSCREENWIDTH-16)/2*1080/1920));
    }
    else if ([base.plates integerValue]==2)
    {
        //坚板
        return CGSizeMake((KSCREENWIDTH-16)/2, ((KSCREENWIDTH-16)/2*1920/1080));
    }
    return CGSizeMake(0, 0);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self hideFilterView];
}

@end
